package com.pvdnc.worldmagisk;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ShellStream {
    private static final ALog LOG=new ALog(ShellStream.class);

    private InputStream stdin;

    OutputStream stdout;

    public ShellStream(Process process){
        stdin= process.getInputStream();
        stdout=process.getOutputStream();
    }

    public ShellStream(InputStream in,OutputStream out){
        stdin=in;
        stdout=out;
    }

    public byte[] execute(String cmd) throws IOException {
        stdout.write(cmd.getBytes());
        stdout.flush();
        return read();
    }

    private byte[] read() throws IOException {
        Callable<byte[]> callable=new Callable<byte[]>() {
            @Override
            public byte[] call() throws IOException {
                int available=stdin.available();
                LOG.d("there are "+available+" bytes to read");
                ByteArrayOutputStream bos=new ByteArrayOutputStream();
                byte[] singleBit=new byte[1];
                while (stdin.read(singleBit)!=-1){
                    bos.write(singleBit);
                }
                LOG.d("stdin read until EOF");
                return bos.toByteArray();
            }
        };
        FutureTask<byte[]> futureTask=new FutureTask<>(callable);
        new Thread(futureTask,"ReadStream").start();
        /*try {
            return futureTask.get();
        } catch (ExecutionException | InterruptedException e) {
            throw new IOException("fail to read from input stream",e);
        }*/
        return "eof".getBytes();
    }

    public void close() throws IOException {
        stdout.flush();
        stdin.close();
    }
}
